package com.sczmgk.hotline_pzh.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import com.sczmgk.hotline_pzh.MyApp;
import com.sczmgk.hotline_pzh.R;
import com.sczmgk.hotline_pzh.callback.SimplePaserJsonCallback;
import com.sczmgk.hotline_pzh.constants.Constants;
import com.sczmgk.hotline_pzh.httputils.MyHttp;
import com.sczmgk.hotline_pzh.sp.CacheUtils;
import com.shizhefei.view.indicator.Indicator;
import com.shizhefei.view.indicator.ScrollIndicatorView;
import com.shizhefei.view.indicator.slidebar.ColorBar;
import com.shizhefei.view.indicator.slidebar.ScrollBar;
import com.shizhefei.view.indicator.transition.OnTransitionTextListener;

import org.apache.commons.lang.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressLint("ShowToast")
public class CommonUtils {

    private static final String TAG = CommonUtils.class.getSimpleName();
    /**
     * 取得手机的Imei
     * @param context
     * @return  返回手机的串号 
     */
    public static String getPhoneImei(Context context){
    	String imei =((TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE)).getDeviceId();
    	return imei.toString();
    }
    /**
     * 取得WifiMAC地址，没开wifi都能得到
     * @param context
     * @return  返回手机WIFI MAC地址
     */
    @SuppressLint("ServiceCast")
	public static String getWifiMac(Context context){
    	WifiManager wifi = (WifiManager)context.getSystemService(Context.TELEPHONY_SERVICE);
    	WifiInfo info = wifi.getConnectionInfo();
    	return info.getMacAddress();
    }
    /**
	 * 取得屏幕宽度
	 * @param context
	 * @return
	 */
	public static int getScreenWidth(Context context) {
		WindowManager manager = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		Display display = manager.getDefaultDisplay();
		return display.getWidth();
	}
	/**
	 * 取得屏幕高度
	 * @param context
	 * @return
	 */
	public static int getScreenHeight(Context context) {
		WindowManager manager = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		Display display = manager.getDefaultDisplay();
		return display.getHeight();
	}
	/**
	 * 取得屏幕像素密度
	 * @param context
	 * @return
	 */
	public static float getScreenDensity(Context context) {
		try {
			DisplayMetrics dm = new DisplayMetrics();
			WindowManager manager = (WindowManager) context
					.getSystemService(Context.WINDOW_SERVICE);
			manager.getDefaultDisplay().getMetrics(dm);
			return dm.density;
		} catch (Exception ex) {

		}
		return 1.0f;
	}

    // private static AlertDialog alertDialog = null;

    public static final int MSG_SHOW_ALERTDIALOG = 1;

    private static List<Activity> activityList = new ArrayList<Activity>();

    /**
     * 转出
     */
    public static final String IP_FLAG_REC = "0";
    /**
     * 转入
     */
    public static final String IP_FLAG_PAY = "1";

    public static final String SHARED_CONFIG_FILE_NAME = "shared_config";
    /**
     * 判断网络是否畅通
     * 
     * @param context
     * @return
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == null) {
            return false;
        } else {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 判断网络是否畅通
     * @param context
     * @return
     */
    public static boolean isWifiNetwork(Context context) {
        boolean is3GNetwork = false;
        ConnectivityManager connec = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connec.getActiveNetworkInfo();
        if (info == null) {
            return false;
        }
        int localNetworkType = info.getType();
        is3GNetwork = ConnectivityManager.TYPE_WIFI == localNetworkType;

        return is3GNetwork;
    }
	/**
	 * 移除Activity
	 * @param activity
	 */
    public static void removeActivity(Activity activity) {
        activityList.remove(activity);
    }

    /**
     * 添加Activity
     * @param activity
     */
    public static void addActivity(Activity activity) {
        activityList.add(activity);
    }

    /**
     * 取得在前台的Activity集合
     * @return
     */
    public static List<Activity> getActivityList() {
        return activityList;
    }

    /**
     * 结束Activity
     */
    public static void finishActivity() {
        for (Activity activity : activityList) {
            activity.finish();
        }
    }

    /**
     * 字符串非空判断
     * 
     * @param s 字符串
     */
    public static boolean StringIsNull(String s) {
        boolean result = false;
        if (null == s || "".equals(s.trim())) {
            result = true;
        }
        return result;
    }

    /**
     * json解析后空字符窜 变成 null，此方法将null字符串 变成空
     * 
     * @param s 字符串
     */
    public static boolean StringReplaceNull(String s) {
        if (StringIsNull(s) || s.equals("null")) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 判断字符串为不为null？字符串：deVanul
     * 
     * @param s 字符串
     */
    public static String getStringFilteNull(String s, String deValue) {
        return StringReplaceNull(s) ? deValue : s;
    }

    /**
     * 存图片到本地
     */
    public static void saveImageLocal(Bitmap bitmap, String url) {

        try {
            // 创建文件夹
            File file = new File(FileUtil.RESOURCE_USER_IMAGE_CACHE_PATH);
            if (!file.exists()) {
                file.mkdirs();
            }
            // 待上传的路径
            String path = FileUtil.RESOURCE_USER_IMAGE_CACHE_PATH + File.separator + url;
            // 存放指定图片
            File f = new File(path);
            FileOutputStream iStream = null;
            iStream = new FileOutputStream(f);
            bitmap.compress(CompressFormat.PNG, 100, iStream);

            iStream.close();
            iStream = null;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Retrieves application's version number from the manifest 版本代码
     * 
     * @return Version
     */
    public static int getVersionCode(Context context) {
        int versionCode = 0;

        PackageManager packageManager = context.getPackageManager();
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            versionCode = packageInfo.versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }

        return versionCode;
    }

    /**
     * Retrieves application's version name from the manifest 版本
     * 
     * @return Version
     */
    public static String getVersionName(Context context) {
        String versionName = null;
        PackageManager packageManager = context.getPackageManager();
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            versionName = packageInfo.versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }

        return versionName;
    }


    /**
     * 
     * @param s
     * @param i
     */
    static void pBinInt(String s, int i) {
        System.out.println(s + ", int: " + i + ", binary: ");
        System.out.print("   ");
        for (int j = 31; j >= 0; j--)
            if (((1 << j) & i) != 0)
                System.out.print("1");
            else
                System.out.print("0");
        System.out.println();
    }



    /**
     * 隐藏软键盘
     */
    public static void hideSoftKeyboard(Activity activity) {
        View view = activity.getCurrentFocus();
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);// 隐藏软键盘
        }
    }



    /**
     * 根据jid获取username
     * 
     * @return
     */
    public static String getUsernameByJid(String jid) {
        if (StringUtils.isEmpty(jid)) {
            return "";
        } else {
            if (jid.contains("@")) {
                return jid.substring(0, jid.indexOf("@"));
            } else {
                return jid;
            }
        }
    }

    /**
     * 获取系统的版本
     * 
     */
    public static int getSDKVersionValue() {
        return android.os.Build.VERSION.SDK_INT;
    }

    /**
     * 标点半角转为全角
     * 
     * @param input 要转的字符串
     * @return 转成功后的字符串
     */
    public static String ToDBC(String input) {
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == 12288) {
                c[i] = (char) 32;
                continue;
            }
            if (c[i] > 65280 && c[i] < 65375)
                c[i] = (char) (c[i] - 65248);
        }
        return new String(c);
    }



    /** * 程序是否在前台运行 * * @return */
    public static boolean isAppOnForeground(Context context) {
        // Returns a list of application processes that are running on the
        // device
        ActivityManager activityManager = (ActivityManager) context.getApplicationContext().getSystemService(
                Context.ACTIVITY_SERVICE);
        String packageName = context.getApplicationContext().getPackageName();
        List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        if (appProcesses == null)
            return false;
        for (RunningAppProcessInfo appProcess : appProcesses) {
            // The name of the process that this object is associated with.
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }
        return false;

    }

/**
 * 获取当前时间
 * @return
 */
    public static String getTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        Date date = new Date();
        return simpleDateFormat.format(date);
    }

    public static String InputStreamTOString(InputStream in, String encoding) throws Exception {

        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        int count = -1;
        while ((count = in.read(data, 0, 1024)) != -1)
            outStream.write(data, 0, count);

        data = null;
        return new String(outStream.toByteArray(), encoding);
    }

    /**
     * 加密session key
     * 
     * @param friendSession
     * @return
     */
    public static String buildSessionKey(String friendSession) {
        if (friendSession == null) {
            return "";
        }
        StringBuilder sb = new StringBuilder(friendSession);
        String fMsg = friendSession + sb.reverse();

        while (fMsg.length() < 24 * 2) {
            fMsg += fMsg;
        }

        StringBuilder fsb = new StringBuilder();
        for (int i = 0; i < 48; i += 2) {
            fsb.append(fMsg.charAt(i));
        }
        return fsb.toString();
    }
    
    /**
     * 拨打电话
     * @param context
     * @param phoneNumber
     */
    public static void callPhone(Context context,String phoneNumber){
    	Intent intent = new Intent();
		intent.setAction(Intent.ACTION_CALL);
		intent.setData(Uri.parse("tel:"+phoneNumber));
		context.startActivity(intent);
    }

    public static void reportImei(final Context context) {
        Map<String,Object> maps = new HashMap<String,Object>();
        maps.put("consumerid", MyApp.loginUserUid);
        maps.put("lastusetime", "");
        maps.put("imei",MyApp.imei);
        maps.put("os_platform",getAndroidVersion());
        maps.put("os_version",getBuildModel());
        MyHttp.requestByReportImei(Constants.BASE_URL + Constants.POST_CONSUMERS_IMEI, maps, MyHttp.POST, context, false,
                null, new SimplePaserJsonCallback() {
            @Override
            public void onVerifyIsNull() {

            }

            @Override
            public void onVerifySuccess(String dataRaw, boolean isCache) {
              MyLog.d(TAG,"单点返回----------------");
                CacheUtils.cacheBooleanData(context, Constants.IS_DISCONNECTION_NETWORK, false);
            }
        });

    }


    private static  String getAndroidVersion(){

        String result = "";
        try {
            //Android 版本号  如: 5.1.1
           String version = android.os.Build.VERSION.RELEASE;
            result = "Android"+version;
            return result;
        } catch (Exception e) {
            return result;
        }

    }

    private  static String getBuildModel(){
        String result = "";
        try {
            //手机型号
          result = android.os.Build.MODEL;
          return result;
        } catch (Exception e) {
            return result;
        }
    }

    private static class MyAdapter extends Indicator.IndicatorAdapter {

        private Activity activity;
        private String[] tabNames;

        public MyAdapter(Activity activity,String[] tabNames) {
            super();
            this.activity = activity;
            this.tabNames = tabNames;
        }

        @Override
        public int getCount() {
            return tabNames.length;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = activity.getLayoutInflater().inflate(R.layout.tab_top, parent, false);
            }
            TextView textView = (TextView) convertView;
            //用了固定宽度可以避免TextView文字大小变化，tab宽度变化导致tab抖动现象
            textView.setWidth(Tools.dip2px(activity, 90));
            textView.setText(tabNames[position]);
            return convertView;
        }
    }
    /**
     * 设置Indecator
     *
     * @param indicator
     * @param tabNames
     * @param activity
     */
    public static void setIndector(Indicator indicator, String[] tabNames, Activity activity) {

        ScrollIndicatorView scrollIndicatorView =  (ScrollIndicatorView)indicator;
        scrollIndicatorView.setSplitAuto(true);
        float density = CommonUtils.getScreenDensity(activity);
        //设置适配器
        indicator.setAdapter(new MyAdapter(activity,tabNames));
        //设置选中的颜色及高度(高度传0时则可以设置全部背景色)
        int heigh = (int)activity.getResources().getDimension(R.dimen.indicator_bottom_line);
        ColorBar colorBar = new ColorBar(activity,activity.getResources().getColor(R.color.common_red_color), heigh, ScrollBar.Gravity.BOTTOM);
        indicator.setScrollBar(colorBar);
        //未选择时文字的大小
        float unSelectSize = (activity.getResources().getDimension(R.dimen.indicator_text_size))/density;
        //选中后文字放大的倍数
        float selectSize = unSelectSize * 1;
        //选择后文字的颜色
        final int selectColor = activity.getResources().getColor(R.color.common_red_color);
        //未选中时文字的颜色
        int unSelectColor = activity.getResources().getColor(R.color.indicator_no_select_color);
        indicator.setOnTransitionListener(new OnTransitionTextListener().setColor(selectColor, unSelectColor).setSize(selectSize, unSelectSize));
        //设置当前选中的位置
        indicator.setCurrentItem(0, true);
    }
}
